<template>
	<view class="the-page">
		<view class="address-item" v-for="(item, i) in addressList" :key="i">

			<view class="check">
				<radio :checked="item.id == chosenAddressId" v-if="isChosenAddress"></radio>
				<text style="padding: 0 10px;" v-else>{{ i+1 }}</text>
			</view>
			<view class="address" @click="onClickRow(item.id)">
				<view class="row-top">
					<view class="name">{{ item.name }}</view>
					<view class="tel">{{ item.tel }}</view>
					<uni-tag text="默认" type="error" size="mini" v-if="item.isDefault"></uni-tag>
				</view>
				<view class="row-bottom">{{ item.address }}</view>
			</view>
			<view class="edit"><uni-icons type="compose" :size="28" color="#999999" @click="onEdit(item.id)"></uni-icons>
			</view>

		</view>
		<button type="primary" @click="onSelect" v-if="!!chosenAddressId">选择</button>
		<button type="primary" @click="onAdd">新建收货地址</button>
	</view>
</template>

<script>
	//获取地址列表
	import * as addressAPI from '@/api/address.js';

	export default {
		data() {
			return {
				chosenAddressId: 0,
				isChosenAddress: false,
				addressList: []
			};
		},
		onLoad(options) {
			this.chosenAddressId = options.addressId || null;
			console.log('onLoad : chosenAddressId ', this.chosenAddressId);
			this.isChosenAddress = !!this.chosenAddressId;
			this.getAddressList();
		},
		onShow() {
			this.getAddressList();
		},
		methods: {
			getAddressList() {
				addressAPI.getMyList().then(result => {
					// console.log(result)
					this.addressList = [];
					result.data.forEach(item => {
						this.addressList.push({
							id: item.id,
							name: item.name,
							tel: item.tel,
							address: item.city + item.county + item.detail,
							isDefault: item.isDefault
						});
					});
				});
			},

			onEdit(id) {
				uni.navigateTo({
					url: '/pages/address/addressEdit?id=' + id,
				});
			},
			onAdd() {
				uni.navigateTo({
					url: '/pages/address/addressEdit'
				});
			},

			onClickRow(id) {
				if (this.isChosenAddress) {
					this.chosenAddressId = id;
				}
			},
			onSelect() {
				//?addressId=" + this.chosenAddressId  参数如何传过去？？？？？？？？
				// 建议通过页面通信，事件监听机制

				// 关闭当前页面，返回上一页面
				uni.navigateBack({
					delta: 1 //url:"/pages/order/orderCreate"
				});
				uni.$emit('addressChanged', { addressId: this.chosenAddressId });
			}
		}
	};
</script>

<style lang="scss" scoped>
	.the-page {
		padding: 15px;
	}

	.address-item {
		display: flex;
		flex-direction: row;
		align-items: center;
		ustify-content: space-between;
		margin: 10px 0;
		padding-bottom: 10px;
		border-bottom: 1px solid $uni-border-color;

		.check .edit {
			padding: 0 10px;
		}

		.address {
			flex: 1;
		}

	}

	.row-top {
		display: flex;
		flex-direction: row;
		font-weight: bold;
		font-size: 16px;

		.tel {
			margin: 0 20px;
		}
	}

	.row-bottom {
		margin-top: 5px;
		font-size: 14px;
		color: $uni-text-color-grey;
	}

	uni-button {
		margin: 10px 0;
	}
</style>